/* Holly Beach & Liviu Patrasco
 *  scheduler.c
 *  Created on: Feb 25, 2012
 */
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include "scheduler.h"

int i;
int priority;
int indexOfLastProcRun = -1;
extern int numberOfProcesses;
extern char schedulingPolicy;
extern process *processes[20];

process *proc;  //a ptr to the process to run

process* getProcess(){
	int indexNo;
	switch (schedulingPolicy){
		case 'R': /*Round Robin scheduling policy.  If there are no runnable*/
		case 'r': /*processes other than lastProcess, lastProcess will be chosen*/
			indexNo = (indexOfLastProcRun + 1) % numberOfProcesses;
			proc = processes[indexNo];
			while (proc->status != RUNNABLE){
				indexNo = (indexNo + 1)% numberOfProcesses;
				proc = processes[indexNo];
			}
			break; // can use do while ===========================
		case 'P':  /*priority scheduling, the runnable process with the*/
		case 'p':  /*highest priority other than the last process*/
			priority = 0;
			indexNo = -1;
			for(i = 0; i<numberOfProcesses; i++){
				if (i != indexOfLastProcRun && processes[i]->status == RUNNABLE &&
						processes[i]->priority > priority){
					priority = processes[i]->priority;
					indexNo = i;
				}
			}
			//if we didn't find any available "other" processes, rerun last proc
			if(indexNo == -1 && processes[indexOfLastProcRun]->status == RUNNABLE)
				indexNo = indexOfLastProcRun;
			proc = processes[indexNo];
			break;

		case 'L':/*lottery scheduling, randomly choose a runnable process*/
		case 'l':
			do {
				indexNo = rand() % numberOfProcesses;
				proc = processes[indexNo];
			} while (processes[indexNo]->status != RUNNABLE);
			break;
	}
	indexOfLastProcRun = indexNo;
	printf("SCHEDULER: running process %d (%s) next.\n",proc->id, proc->strName);
	fflush(stdout);
	return proc;
}


